package com.yishun.springboot.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yinquan.util.ParseGwsResult;
import com.yishun.springboot.pojo.GwsDictListJobName;
import com.yishun.springboot.pojo.GwsTeamType;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 发送层-可直接调用的数据上报方法
 *
 * @author XiaoHuang
 * @date 2021年3月22日 下午3:13:53
 */
@Slf4j
@Service
@Component
public class InnerFormalGWSCWRService {

	// 是否详细记录
	static Boolean detailedRecordLong = true;

	// 已修改为正确的
	public String api_key = "57eaea5815fa434dad3d3f374700d2c6";// √
	public String api_secret = "5ebe9d8d12694734be46f9fcbf2955c5";// √
	public String client_serial = "57eaea5815fa434dad3d3f374700d2c6";// √
	public String api_version = "1.0";// √
	public String Project_ID = "DESY-016-2019";// 工程编码 //√

	// 正确的
	public String timestamp = "2020-12-03 19:26:15";// √

	// 无关紧要(须动态引入，paramJson内填写)
	// public String companyName = "";// 分包商/企业名称（需提交资料给工务署人员入库）
	// public String SUID = "";// 分包商/企业营业执照号

	/**
	 * step1添加参建单位×（工务署平台已经废除该接口）
	 */
	// public String addCompany(JSONObject bodyjson,String apiKey,
	// String apiSecret,String clientSerial,String apiVersion,
	// String timestamp) {
	// String url = "http://szwb.sz.gov.cn:2018/CWRService/AddCompany";
	////
	// String body = bodyjson.toString();
	// String signature = getSignature(api_secret, body, api_key, api_version,
	// client_serial, timestamp);
	// Map<String, Object> param = new HashMap<>();
	// param.put("api_version", api_version);
	// param.put("client_serial", client_serial);
	// param.put("api_key", api_key);
	// param.put("timestamp", timestamp.toString());
	// param.put("signature", signature.toString());
	// param.put("body", body);
	// String info = HttpUtil.post(url, param);
	// log.info(info);
	// return info;
	// }

	/**
	 * step2实名制-获取工种 √
	 *
	 * @throws NoSuchAlgorithmException
	 */
	public List<GwsDictListJobName> getDictListJobName() throws NoSuchAlgorithmException {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/DictListJobName";// 获取工种类型
		HashMap<String, Object> json = new HashMap<String, Object>();
		List<GwsDictListJobName> list = new ArrayList<GwsDictListJobName>();

		json.put("api_key", api_key);
		json.put("api_version", "1.0");
		json.put("client_serial", client_serial);
		json.put("timestamp", timestamp);
		json.put("body", "{}");
		String signature = getSignature(api_secret, (String) json.get("body"), (String) json.get("api_key"),
				(String) json.get("api_version"), (String) json.get("client_serial"), (String) json.get("timestamp"));
		json.put("signature", signature);
		log.info(JSONObject.toJSONString(json));
		String info = HttpUtil.post(url, json);
		log.info("info:" + info);
		JSONObject jsonObject = JSON.parseObject(info);
		String a = jsonObject.getString("result_data");
		JSONObject jsonObject2 = JSON.parseObject(a);
		String a2 = jsonObject2.getString("dict_list");
		JSONArray JsonArray = JSON.parseArray(a2);
		for (int i = 0; i < JsonArray.size(); i++) {
			String a3 = JsonArray.get(i).toString();
			GwsDictListJobName d = JSON.parseObject(a3, GwsDictListJobName.class);
			if (d.getValue().equals("其他") | d.getOrders().equals("040")) {
				System.out.println();
			}
			;
			list.add(d);
		}
		return list;
		// 不用bean用什么获取result_data内容？
		// 工種類型：orders":"26","value":"电焊工","workerPostType":"COMMON","workerPostTypeName":"一般作业工种"},{"orders":"27","value":"爆破工",
		// 班組類型：[{"orders":"CONCRETE","value":"混凝土班","orderNum":0.0},{"orders":"waterproof","value":"防水班","orderNum":0.0,"typeAttribute":"00"}..]
	}

	public static void main(String[] args) {
		InnerFormalGWSCWRService formalGWSCWRService = new InnerFormalGWSCWRService();
		try {
			System.out.println(formalGWSCWRService.getDictListJobName());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * step3 实名制-获取班组类型 √
	 *
	 * @throws NoSuchAlgorithmException
	 */
	public List<GwsTeamType> GetTeamType() throws NoSuchAlgorithmException {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/GetTeamType";// 获取班组类型
		HashMap<String, Object> json = new HashMap<String, Object>();
		List<GwsTeamType> list = new ArrayList<GwsTeamType>();
		json.put("api_key", api_key);
		json.put("api_version", "1.0");
		json.put("client_serial", client_serial);
		json.put("timestamp", timestamp);
		json.put("body", "{}");
		String signature = getSignature(api_secret, (String) json.get("body"), (String) json.get("api_key"),
				(String) json.get("api_version"), (String) json.get("client_serial"), (String) json.get("timestamp"));
		json.put("signature", signature);
		log.info(json.toString());
		String info = HttpUtil.post(url, json);
		log.info("info:" + info);
		JSONObject jsonObject = JSON.parseObject(info);
		String a = jsonObject.getString("result_data");
		JSONObject jsonObject2 = JSON.parseObject(a);
		String a2 = jsonObject2.getString("dict_list");
		JSONArray JsonArray = JSON.parseArray(a2);
		for (int i = 0; i < JsonArray.size(); i++) {
			String a3 = JsonArray.get(i).toString();
			GwsTeamType t = JSON.parseObject(a3, GwsTeamType.class);
			list.add(t);
			log.info("bean:" + t.toString());
		}
		return list;

		// 不用bean用什么获取result_data内容？
		// 工種類型：orders":"26","value":"电焊工","workerPostType":"COMMON","workerPostTypeName":"一般作业工种"},{"orders":"27","value":"爆破工",
		// 班組類型：[{"orders":"CONCRETE","value":"混凝土班","orderNum":0.0},{"orders":"waterproof","value":"防水班","orderNum":0.0,"typeAttribute":"00"}..]
	}

	/**
	 * step4 实名制-新增班组√ AddTeam接口
	 *
	 * @param json
	 * @param api_secret
	 * @param api_key
	 * @param api_version
	 * @param client_serial
	 * @param timestamp
	 * @return
	 */
	public String addTeam(JSONObject json, String api_secret, String api_key, String api_version, String client_serial,
			String timestamp) {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/AddTeam";
		String info = "";
		String body = json.toString();
		Map<String, Object> param = new HashMap<>();
		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			info = HttpUtil.post(url, param);
			if (detailedRecordLong) {
				log.info("------------------------------");
				log.info("请求地址:" + url);
				log.info("header:" + param);
				log.info("请求体:" + json);
				log.info(info);
				log.info("------------------------------\n\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
		// {"team_id":"6014985e9877f6dfc0633b0601ce2612","team_name":"渣渣輝"}}
	}

	/**
	 * step5 实名制-上传图片√√ 这个不用大改，所以直接打了第二个√，该是什么样就什么样
	 */
	public String UploadImage(String apiKey, String filePath) {

		if (filePath == null)
			return null;

		ParseGwsResult parseGwsResult = new ParseGwsResult();
		File file = null;
		// File file = new File("C:\\Users\\Administrator\\Desktop\\3.JPG");
		file = new File(filePath);
		String url = "http://szwb.sz.gov.cn:2018/CWRService/UploadImage";
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", apiKey);
		param.put("file", file);

		String info = HttpUtil.post(url, param);
		if (detailedRecordLong) {
			log.info("请求参数：" + param.toString());
			log.info("结        果：" + info);
		}
		if (parseGwsResult.parseResultsCode(info).equals("00")
				&& parseGwsResult.parseResultsMessage(info).equals("成功")) {
			return JSON.parseObject(parseGwsResult.parseResultsData(info)).getString("image_id");
		} else {
			log.info("上传图片失败,原因：" + parseGwsResult.parseResultsMessage(info));
			log.info("请求体：" + param);
			return null;
		}
	}

	// 获取文件，因为web需要而不是路径
	public String UploadImage(MultipartFile multipartFile) {

		String fileName = multipartFile.getOriginalFilename();
		File file = new File(fileName);
		log.info("files:" + file.getPath());
		OutputStream out = null;
		try {
			// 获取文件流，以文件流的方式输出到新文件
			// InputStream in = multipartFile.getInputStream();
			out = new FileOutputStream(file);
			byte[] ss = multipartFile.getBytes();
			for (int i = 0; i < ss.length; i++) {
				out.write(ss[i]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// File file = new File("C:\\Users\\Administrator\\Desktop\\3.JPG");
		String url = "http://szwb.sz.gov.cn:2018/CWRService/UploadImage";
		Map<String, Object> param = new HashMap<>();
		param.put("api_key", api_key);
		param.put("file", file);
		String info = HttpUtil.post(url, param);
		log.info(info); // 每次上傳如果相同的照片，返回的image_id也不同

		JSONObject jsonObject = JSON.parseObject(info);
		String results = jsonObject.getString("result_data");

		return results;

		// {"result":"true","code":"00","status":"200","message":"成功","result_data":{"image_id":"8fc3c24d06b59e19fc211c3b5bf1113c"}}
	}

	/**
	 * step6 实名制-上报人员实名制信息
	 */
	public String RegisterEmployee(JSONObject json, String api_secret, String api_key, String api_version,
			String client_serial, String timestamp) {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/RegisterEmployee";
		String body = json.toString();
		String info = "";
		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			info = HttpUtil.post(url, param);
			log.info(info);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return info;
	}

	/**
	 * step7 实名制-上传考勤信息
	 */
	public String UploadPassedLog(JSONObject json) {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/UploadPassedLog";// 不知道什么呢
		String info = null;
		String body = json.toString();
		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			info = HttpUtil.post(url, param);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return info;
	}

	/**
	 * step7 实名制-人员离场√
	 */
	public String userLeaveProject(JSONObject json) {
		String url = "http://szwb.sz.gov.cn:2018/CWRService/userLeaveProject";
		String info = null;
		String body = json.toString();
		try {
			String signature = getSignature(api_secret, body, api_key, api_version, client_serial, timestamp);
			Map<String, Object> param = new HashMap<>();
			param.put("api_version", api_version);
			param.put("client_serial", client_serial);
			param.put("api_key", api_key);
			param.put("timestamp", timestamp);
			param.put("signature", signature);
			param.put("body", body);
			info = HttpUtil.post(url, param);
			log.info(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
	}

	public String parseResultsMessage(String info) {
		if (!isJsonStrByFastjson(info))
			return null;
		JSONObject tempObjetc = JSON.parseObject(info);
		if (tempObjetc == null)
			return null;
		return tempObjetc.getString("message");
	}

	public String parseResultsCode(String info) {
		if (!isJsonStrByFastjson(info))
			return null;
		JSONObject tempObjetc = JSON.parseObject(info);
		if (tempObjetc == null)
			return null;
		return tempObjetc.getString("code");
	}

	public String parseResultsData(String info) {
		if (!isJsonStrByFastjson(info))
			return null;
		return JSON.parseObject(info).getString("result_data");
	}

	// 工务署参数get setteer
	public String getApi_key() {
		return api_key;
	}

	public void setApi_key(String api_key) {
		this.api_key = api_key;
	}

	public String getApi_secret() {
		return api_secret;
	}

	public void setApi_secret(String api_secret) {
		this.api_secret = api_secret;
	}

	public String getClient_serial() {
		return client_serial;
	}

	public void setClient_serial(String client_serial) {
		this.client_serial = client_serial;
	}

	public String getApi_version() {
		return api_version;
	}

	public void setApi_version(String api_version) {
		this.api_version = api_version;
	}

	public String getProject_ID() {
		return Project_ID;
	}

	public void setProject_ID(String project_ID) {
		Project_ID = project_ID;
	}

	/**
	 * @param api_secret
	 *            授权秘钥
	 * @param body
	 *            请求体
	 * @param api_Key
	 *            授权帐号
	 * @param api_Version
	 *            API协议版本
	 * @param client_Serial
	 *            第三方系统编号 可以取值
	 * @param timeStamp
	 *            时间戳，格式为yyyy-MM-dd hh:mm:ss
	 * @return boolean
	 * @Description:拼接加密参数
	 * @author fanghe 2017年3月25日 上午11:44:50
	 */
	private static String getSignature(String api_secret, String body, String api_Key, String api_Version,
			String client_Serial, String timeStamp) {
		StringBuilder str4MD5 = new StringBuilder();
		str4MD5.append(api_secret).append("api_key").append(api_Key).append("api_version").append(api_Version)
				.append("body").append(StrUtil.isEmpty(body) ? "{}" : body).append("client_serial")
				.append(client_Serial).append("timestamp").append(timeStamp).append(api_secret);
		// log.info(str4MD5.toString());
		String str = GetMD5Code(str4MD5.toString());
		return str;
	}

	/**
	 * Description: 获取32位大写MD5加密
	 *
	 * @param strObj
	 *            原文
	 * @return 32位大写MD5加密
	 * @see
	 */
	public static String GetMD5Code(String strObj) {
		String resultString = null;
		resultString = new String(strObj);
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Charset charset = Charset.forName("UTF-8");
		// md.digest() 该函数返回值为存放哈希值结果的byte数组
		resultString = byteToString(md.digest(strObj.getBytes(charset)));
		return resultString;
	}

	/**
	 * Description: 转换字节数组为16进制字串
	 *
	 * @param bytes
	 *            字节数组
	 * @return 16进制字串
	 * @see
	 */
	private static String byteToString(byte[] bytes) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			sBuffer.append(byteToArrayString(bytes[i]));
		}
		return sBuffer.toString();
	}

	/**
	 * Description: 返回形式为数字跟字符串(大写)
	 *
	 * @param bByte
	 *            字节
	 * @return 返回形式为数字跟字符串(大写)
	 * @see
	 */
	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	/**
	 * 全局数组
	 */
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
			"E", "F" };

	/**
	 * 签名的生成 签名测试
	 *
	 * @throws NoSuchAlgorithmException
	 */
	public void createSignature() {
		String signature = getSignature(api_secret,
				"{\"entry_time\":\"2019-07-01 02:56:05\",\"Legal_Person\":\"罗世威\",\"Type\":\"009\",\"Project_ID\":\"XM2013031101\",\"Company_Name\":\"中国建筑一局(集团)有限公司\"}",
				api_key, api_version, client_serial, timestamp);
		log.info(signature);
		// 如果body为空
		String signature2 = getSignature(api_secret, null, api_key, api_version, client_serial, timestamp);
		log.info(signature2);
	}

	public static boolean isJsonStrByFastjson(String str) {
		try {
			JSONObject jsonElement = JSONObject.parseObject(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}
